//
//  ZUserAccountViewModel.swift
//  swift-weibo
//
//  Created by zero on 17/3/23.
//  Copyright © 2017年 zero. All rights reserved.
//

import UIKit

private let userInfoPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userInfo.plist")


class ZUserAccountViewModel: NSObject {

    //  单例
    static let shareUserAccoutn = ZUserAccountViewModel()
    
    
    var account:ZUserInfoModel?
    
    //  获取一次account
    private override init() {
        
        super.init()
        
        account = self.uploadUserInfo()
        
    }
    

    var headURL: URL? {
        return URL(string: account?.avatar_large ?? "")
    }
    

    var userLogin: Bool {
        
        if account?.access_token != nil && isExpires == false {
            return true
        }
        
        //默认用户没有登录
        return false
    }
    
    
    var isExpires: Bool {

        if account?.expires_date?.compare(Date()) == .orderedDescending {
            return false
        }
        //默认过期
        return true
    }

    //  根据code获取token
    
    func getToken(code:String, finish:@escaping (_ res:Bool) -> ()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let para = ["client_id" : client_id,
                    "client_secret" : client_secret,
                    "grant_type" : "authorization_code",
                    "code" : code,
                    "redirect_uri" : redirect_uri]
        
        ZNetworkTools.shared.request(method: .POST, urlString: urlString, paramters: para) { (res, error) in
            
            if (error != nil){
                
                finish(false)
            }else{
                
                //  根据token来获取用户数据
                self.getUserInfo(dic: res as! [String : Any],finish: finish)
            }
        }
        
        
    }
    
    //  获取用户信息
    private func getUserInfo(dic:[String : Any],finish:@escaping (_ res:Bool) -> ()){
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let token = dic["access_token"]!
        let uid = dic["uid"]!
        
        let para = ["access_token" : token,
                    "uid": uid]
        
        ZNetworkTools.shared.request(method: .GET, urlString: urlString, paramters: para) { (res, error) in
            
            if error != nil{
                
                finish(false)
            }else{
                
                var userInfoDict = res as! [String : Any]
                
                for (key , value) in dic{
                    
                    userInfoDict[key] = value
                }
                
                self.account = ZUserInfoModel(dic: userInfoDict)
                
                //  归档
                self.saveUserInfo(account: self.account!)
                
                finish(true)
            }
        }
    }
    
    
    //  归档
    private func saveUserInfo(account: ZUserInfoModel){
        
        NSKeyedArchiver.archiveRootObject(account, toFile: userInfoPath)
        
    }
    
    //  接档
    private func uploadUserInfo() -> ZUserInfoModel?{
        
        let model = NSKeyedUnarchiver.unarchiveObject(withFile: userInfoPath)
        
        if let m = model as? ZUserInfoModel {
            
            return m
        }
        
        return nil
        
    }
}
